<script setup>
import {ref, onMounted} from 'vue';
import XYZ from "ol/source/XYZ";
import {Map, View} from "ol";
import TileLayer from "ol/layer/Tile";
import {MousePosition} from 'ol/control'
import {createStringXY} from "ol/coordinate";
const map =  ref(null);
const position = ref(null)

const mousePositionCtl = ()=>{
  console.log(position.value,'value')
  const mousePositionControl = new MousePosition({
    // 坐标格式 ， 函数是保留多少位小数点
    coordinateFormat: createStringXY(9),
    //坐标的投影默认使用的是view视图的投影
    projection: 'EPSG:4326',
    //坐标信息显示样式类名，默认是'ol-mouse-position'
    className: 'custom-mouse-position',
   // 指定鼠标控件挂载的位置
    target: position.value,
    // 未定义的左边的标记
    placeholder: '未识别鼠标位置',
    //重新呈现控件时调用的函数
    // render函数必须是执行的函数
    render: render()

  })
  map.value.addControl(mousePositionControl);
}

function render(){
  console.log('渲染了')
}

const initMap = ()=>{
  map.value = new Map({
    target: 'map',
    layers: [
        new TileLayer({
          source: new XYZ({url: "http://t4.tianditu.com/DataServer?T=vec_w&x={x}&y={y}&l={z}&tk=d30d1c34260f2edc72b25f9985e2fd69"}),
          name: '位置控制图'
        })
    ],
    // controls: defaultControls(),
    view: new View({
      center: [113.24981689453125, 23.126468438108688], //视图中心位置
      projection: "EPSG:4326",
      zoom: 13
    })
  })
  mousePositionCtl();
}

onMounted(()=>{
  initMap();
})
</script>

<template>
  <div id="map">
    <div id="mouse-position" ref="position">
    </div>
  </div>
</template>

<style scoped>
#map{
  width: 100%;
  height: 100%;
  position: relative;
}

#mouse-position{
  position: absolute;
  left: 50px;
  bottom: 50px;
  z-index: 999;
  background-color: rgba(255, 255, 255, 0.7);
  padding: 5px 10px;
  border: 1px solid #ccc;
  border-radius: 4px;
  font-size: 14px;
  color: #333;
}
</style>